package com.huishu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huishu.commons.pojo.Result;
import com.huishu.commons.utlis.BeanUtils;
import com.huishu.commons.utlis.JwtUtil;
import com.huishu.commons.utlis.PasswordUtil;
import com.huishu.user.mapper.AdminUserMapper;
import com.huishu.user.mapper.RoleMapper;
import com.huishu.user.mapper.UserRoleMapper;
import com.huishu.user.pojo.dto.PageListDTO;
import com.huishu.commons.pojo.model.AdminUserDO;
import com.huishu.user.pojo.model.RoleDO;
import com.huishu.user.pojo.model.UserRoleDO;
import com.huishu.user.pojo.vo.AdminLoginVO;
import com.huishu.user.pojo.vo.AdminUserVO;
import com.huishu.user.pojo.vo.MenuVO;
import com.huishu.user.service.AdminUserService;
import com.huishu.user.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author generator@ljj
 * @since 2023-04-21
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUserDO> implements AdminUserService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Result adminLogin(AdminUserDO adminLoginDTO) {
        AdminUserDO user = baseMapper.selectOne(new QueryWrapper<AdminUserDO>().lambda().and(obj -> obj
                .eq(AdminUserDO::getAccount, adminLoginDTO.getAccount())
                .eq(AdminUserDO::getIsEnable, 1)));
        if (user == null) {
            return Result.fail("账号未注册！");
        }
        if (!PasswordUtil.verify(adminLoginDTO.getPassword(), user.getPassword())) {
            return Result.fail("密码错误！");
        }
        if (!user.getIsEnable()) {
            return Result.fail("非法账户！");
        }
        AdminLoginVO adminLoginVO = BeanUtils.copyProperties(user, AdminLoginVO.class);
        adminLoginVO.setToken(JwtUtil.createAdminUserToken(adminLoginVO.getId(), adminLoginDTO.getPassword()));
        List<MenuVO> menuList = menuService.getMenuList(user.getId());
        if (CollectionUtils.isEmpty(menuList)) {
            return Result.fail("无权限访问");
        }
        adminLoginVO.setMenuList(menuList);
        return Result.success(adminLoginVO);
    }

    @Override
    public Result pageList(PageListDTO pageListDTO) {
        IPage<AdminUserVO> adminUserDOPage = this.baseMapper.pageList(new Page<>(pageListDTO.getCurrPage(), pageListDTO.getPageSize()), pageListDTO);
        List<AdminUserVO> records = adminUserDOPage.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return Result.success();
        }
        List<Long> ids = records.stream().map(AdminUserVO::getId).collect(Collectors.toList());
        LambdaQueryWrapper<UserRoleDO> queryWrapper = Wrappers.lambdaQuery(UserRoleDO.class)
                .in(UserRoleDO::getUserId,ids);
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(userRoleDOS)){
            return Result.success(adminUserDOPage);
        }
        Map<Long, List<UserRoleDO>> userRoleMap = userRoleDOS.stream().collect(Collectors.groupingBy(UserRoleDO::getUserId));
        List<Long> roleIds = userRoleDOS.stream().map(UserRoleDO::getRoleId).collect(Collectors.toList());
        List<RoleDO> roleDOS = roleMapper.selectBatchIds(roleIds);
        Map<Long, List<RoleDO>> roleMap = roleDOS.stream().collect(Collectors.groupingBy(RoleDO::getId));
        for (AdminUserVO record : records) {
            List<UserRoleDO> userRole = userRoleMap.get(record.getId());
            for (UserRoleDO userRoleDO : userRole) {
                AdminUserVO.Role roleVO = new AdminUserVO.Role();
                List<RoleDO> role = roleMap.get(userRoleDO.getRoleId());
                roleVO.setRoleId(role.get(0).getId());
                roleVO.setRoleName(role.get(0).getName());
                record.getRoles().add(roleVO);
            }
        }
        adminUserDOPage.setRecords(records);
        return Result.success(adminUserDOPage);
    }
}
